/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the srsb4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.zyw.srsb.admin.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyw.srsb.admin.config.AliOssConfig;
import com.zyw.srsb.admin.entity.SysImage;
import com.zyw.srsb.admin.mapper.SysImageMapper;
import com.zyw.srsb.admin.service.SysImageService;
import com.zyw.srsb.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 图片管理
 *
 * @author 朱耀威
 * @date 2021-12-15 00:45:22
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysImageServiceImpl extends ServiceImpl<SysImageMapper, SysImage> implements SysImageService {

	private final AliOssConfig aliOssConfig;
	/**
	 * 新增图片
	 *
	 * @param file
	 * @param fileName
	 * @return
	 */
	@Override
	public R save(MultipartFile file, String fileName) {
		String pyFileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		String endpoint = aliOssConfig.getEndpoint();
		String accessKeyId = aliOssConfig.getAccessKeyId();
		String accessKeySecret = aliOssConfig.getAccessKeySecret();
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		String format = f.format(new Date());
		StringBuilder path = new StringBuilder().append(aliOssConfig.getImagePath()).append("/").append(format).append("/").append(pyFileName);
		try {
			PutObjectRequest putObjectRequest = new PutObjectRequest(aliOssConfig.getBucket(), path.toString(), file.getInputStream());
			ossClient.putObject(putObjectRequest);
			// 上传完毕之后构造SysImage对象
			SysImage sysImage = new SysImage();
			sysImage.setFileName(pyFileName);
			sysImage.setOriginal(fileName);
			String url = aliOssConfig.getBaseUrl()+"/"+path.toString();
			sysImage.setImgUrl(url);
			sysImage.setThumbUrl(url);
			sysImage.setType(FileUtil.extName(file.getOriginalFilename()).toUpperCase());
			sysImage.setFileSize(file.getSize());

			// 文件管理数据记录,收集管理追踪文件
			fileLog(sysImage);
		}catch (IOException e){
			log.info("{}",e);
			return R.failed();
		}finally {
			ossClient.shutdown();
		}

		return R.ok();

	}

	/**
	 * 根据id删除指定图片
	 *
	 * @param id
	 * @return
	 */
	@Override
	public Boolean deleteImage(Long id) {
		SysImage sysImage = this.baseMapper.selectById(id);
		if (ObjectUtils.isEmpty(sysImage)){
			return true;
		}
		String endpoint = aliOssConfig.getEndpoint();
		String accessKeyId = aliOssConfig.getAccessKeyId();
		String accessKeySecret = aliOssConfig.getAccessKeySecret();
		String bucketName = aliOssConfig.getBucket();
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		try {
			ossClient.deleteObject(bucketName,sysImage.getImgUrl().replace(aliOssConfig.getBaseUrl()+"/",""));
			this.removeById(id);
		}catch (Exception e){
			return false;
		} finally {
			ossClient.shutdown();
		}
		return true;
	}

	/**
	 * 图片日志
	 * @param sysImage
	 */
	private void fileLog(SysImage sysImage){
		this.save(sysImage);
	}
}
